import reqAddress from '../req-set.js'

let state = {
	search_itemList: [],

}
let mutations = {
	setSearch_itemList(state, v) {
		state.search_itemList = v
	},
	setSearch_itemLoadMoreL(state, v) {
		state.search_itemList = state.search_itemList.concat(v)
	},
	
}
let actions = {
	reqSearchItemList(store, param) {
		store.commit('setSearch_itemList', '')
		return new Promise((resolve, reject) => {
			uni.request({
				method: 'GET',
				url: `${reqAddress}/search`,
				data: {
					kw: param.kw,
					pag: 1
				},
				success: (resp) => {
					let mutaion = 'setSearch_itemList'

					let temp = goodesDataHandle(store, resp, param.active, mutaion)
					resolve(temp)
				},
				fail: (err) => {
					console.log(err)
				}
			})
		})
	},

	reqSearchItemLoadMore(store, param) {
		let page = Math.ceil(store.state.search_itemList.length / 20 + 1)
		return new Promise((resolve, reject) => {
			uni.request({
				method: 'GET',
				url: `${reqAddress}/search`,
				data: {
					kw: param.kw,
					pag: page
				},
				success: (resp) => {
					let mutaion = 'setSearch_itemLoadMoreL'

					let temp = goodesDataHandle(store, resp, param.active, mutaion)
					resolve('成功')
				},
				fail: (err) => {
					console.log(err)
				}
			})
		})
	}
}
//商品列表数据处理函数
function goodesDataHandle(store, resp, param, mutaion) {
	let temp = resp.data.result_list.map_data
	//渲染时使用 ---------- --- --- -  -
	for (let i = 0; i < temp.length; i++) {
		temp[i].src = 'https://img.alicdn.com/bao/uploaded/i2/915497723/O1CN01Cqq4tK26vBNKEzU6M_!!0-item_pic.jpg'
		temp[i].show = true
		temp[i].loaded = false
	}
	switch (param) {
		case 0:
			store.commit(mutaion, temp)
			return temp
		case 1:
			let caseOne = temp.sort((n, m) => {
				if (n.coupon_amount * 1 > m.coupon_amount * 1) {
					return -1
				} else if (n.coupon_amount * 1 < m.coupon_amount * 1) {
					return 1
				} else {
					return 0
				}
			})
			store.commit(mutaion, caseOne)
			return caseOne
		case 2:
			let caseTwo = temp.sort((n, m) => {
				if (n.volume * 1 > m.volume * 1) {
					return -1
				} else if (n.volume * 1 < m.volume * 1) {
					return 1
				} else {
					return 0
				}
			})
			store.commit(mutaion, caseTwo)
			return caseTwo
		case 3:
			let caseThree = temp.sort((n, m) => {
				if (n.coupon_start_fee * 1 > m.coupon_start_fee * 1) {
					return 1
				} else if (n.coupon_start_fee * 1 < m.coupon_start_fee * 1) {
					return -1
				} else {
					return 0
				}
			})
			store.commit(mutaion, caseThree)
			return caseThree
		default:
			return ''
	}
}
const search_idx = {
	state,
	mutations,
	actions
}
export default search_idx
